﻿
// Validate US datetime
function isDateUS(value) {
    var check = false;
    if (value.match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
        var adata = value.split('/');
        var mm = parseInt(adata[0], 10);
        var dd = parseInt(adata[1], 10);
        var yyyy = parseInt(adata[2], 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
            check = true;
        else
            check = false;
    } else {
        check = false;
    }
    return check;
}

// Validate datetime
function isDateTime(a) {
    var a = new Date(a);
    return ($.isNumeric(a.getTime()));
}

// Parse datetime to number
function parseDateTime(a) {
    var a = new Date(a);
    return (a.getTime());
}

// Get current date with format : "mm/dd/yy"
function getCurrentDate() {
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return (month + "/" + day + "/" + year)
}

// Function handle all cross links
// contain ajax helper class to
// using for ajax action link request
function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

//cheeck for Decimal
function IsDecimal(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function ShowMessage(message) {
    $("#message").html(message);
    ShowDialog(true);
}

function isNumberKey(evt) {
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function isPhoneExtNumber(evt) {
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    // check charcode, it's ok if user enter space,(,),-, del character (charCode for + is 43)
    if (charCode == 32 || charCode == 45 || charCode == 46)
        return true;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function isPhoneNumber(evt) {
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    // check charcode, it's ok if user enter space,(,),-, del character (charCode for + is 43)
    if (charCode == 32 || charCode == 40 || charCode == 41 || charCode == 45 || charCode == 46)
        return true;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function isCostKey(evt) {
    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    // "Home" , "End"
    if (charCode == 35 || charCode == 36)
        return true;

    // "Del,.=46", "left arrow=37" , "right arrow=39"
    if (charCode == 46 || charCode == 37 || charCode == 39)
        return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function isAreaKey(evt) {

    evt = evt || window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    // "Home" , "End"
    if (charCode == 35 || charCode == 36)
        return true;

    // "Del,.=46", "left arrow=37" , "right arrow=39"
    if (charCode == 46 || charCode == 37 || charCode == 39)
        return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

// Display preview Terms
function displayDialogTerms(model) {
    $("#overlay").show();
    $("#dialog").fadeIn(300);

    if (modal) {
        $("#overlay").unbind("click");
    }
    else {
        $("#overlay").click(function (e) {
            HideDialog("");
        });
    }
}

function ShowDialog(modal, modalName) {
    $("#overlay" + modalName).show();
    $("#dialog" + modalName).fadeIn(300);

    if (modal) {
        $("#overlay" + modalName).unbind("click");
    }
    else {
        $("#overlay" + modalName).click(function (e) {
            HideDialog(modalName);
        });
    }
}

function ShowDialogError(modal) {
    $("#overlay").show();
    $("#dialogError").fadeIn(300);

    if (modal) {
        $("#overlay").unbind("click");
    }
    else {
        $("#overlay").click(function (e) {
            HideDialogError();
        });
    }
}

function HideDialog(modalName) {
    $("#overlay" + modalName).hide();
    $("#dialog" + modalName).fadeOut(300);
}

function HideDialogError() {
    $("#overlay").hide();
    $("#dialogError").fadeOut(300);
}

/*
Load Email Template Using JSON
Calculate pagesize, pagecurrent, list items
When user change pagesize and pagecurrent

*/

$(document).ready(function () {

    $(".preview").fancybox({
        maxWidth: 700,
        maxHeight: 600,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: true,
        closeClick: true,
        openEffect: 'none',
        closeEffect: 'none'
    });
    /*
    $(".various").fancybox({
    maxWidth: 800,
    maxHeight: 600,
    fitToView: false,
    height: '70%',
    autoSize: true,
    closeClick: true,
    openEffect: true,
    closeEffect: 'none'
    });
    */
    $(".various").each(function () {
        $(this).click(function () {
            var has = $(this).attr("href").replace('#', '');

            var w_Popup;
            var h_Popup;
            if (has.toString() == "ContactUs") {
                w_Popup = 600;
                h_Popup = 275;
            }
            else if (has.toString() == "AboutUs") {
                w_Popup = 600;
                h_Popup = 290;
            }
            else {
                w_Popup = 600;
                h_Popup = 450;
            }

            var url = "/Home/" + has,
		    widthPopup = w_Popup,
		    heightPopup = h_Popup,
		    leftPopup = (screen.width / 2) - (widthPopup / 2),
		    topPopup = (screen.height / 2) - (heightPopup / 2);
            window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup + ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=1,toolbar=0,status=0');

            /*$('.fancybox-skin').show();
            $('#fancybox-overlay').show();
            $.fancybox($('#' + has), {
            padding: 0,
            closeBtn: true,
            helpers: {
            overlay: {
            opacity: 0.6,
            css: {
            'background-color': '#11619D'
            }
            }
            },
            beforeClose: function () {
            return true;
            }
            });
            return false;*/
        });
    });


    $("#checklisence").fancybox({
        maxWidth: 550,
        maxHeight: 500,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: true,
        closeClick: true,
        openEffect: 'none',
        closeEffect: 'none'
    });
    /**/
});

function LoadEmailTemplate(button) {
    // Get change values
    var pageSize = parseInt($('#pageSize').val());
    var pageCurrent = parseInt($('#pageCurrent').val());
    var totalPage = parseInt($('#totalPage').html());

    if (button == 'previous') {
        if (pageCurrent >= 2)
            pageCurrent -= 1;
    }
    else if (button == 'next') {
        if (pageCurrent < totalPage)
            pageCurrent += 1;
    }
    else if (button == 'refresh') {
        pageCurrent = 1;
    }

    // Using ajax loading to bind
    $.getJSON('/Email/GetAllEmailTemplate/' + pageSize + '/' + pageCurrent, function (data) {
        // Bind data to view
        if (data != null) {
            $('#pageSize').val(data.PageSize);
            $('#pageCurrent').val(data.CurrentPage);
            $('#totalPage').html(data.TotalPage)

            // Remove all items in table view
            var items = $('#tableGridView tr');
            $.each(items, function (i) {
                if (i > 0)
                    $(this).remove();
            });

            // Append items
            var arr;
            var statusLabel;
            var table = $("#tableGridView tbody");
            $.each(data.Data, function (i, item) {
                arr = "";
                arr = arr + "<td>" + item.TemplateTitle + "</td>";
                arr = arr + "<td>" + item.Delivery + "</td>";
                arr = arr + "<td><a href='##" + item.TemplateId + "' class='preview'>Preview</a></td>";
                if (item.Status == 'Enabled')
                    statusLabel = 'Yes';
                else
                    statusLabel = 'No';
                arr = arr + "<td align='center'><a href='##" + item.TemplateId + "' class='enable ajaxhelper'>" + statusLabel + "</a></td>";
                table.append("<tr>" + arr + "</tr>");
            });
        }
    });

    return false;
}

// Assign a lead to other users
// Show dialog to select user
// Update assign to user seleted
function doAssignLeadLinks() {
    if (document.getElementsByTagName) {
        var links = document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if (links[i].className.match("cfassign")) {
                links[i].onclick = function () {
                    var leadId = this.getAttribute("href").replace("##", "");
                    var leadName = this.getAttribute("rel");

                    // Update status
                    AssignLead(leadId, leadName);

                    return false;
                };
            }
        }
    }
}

function AssignLead(leadId, leadName) {
    $("#viewleadId").val(leadId);
    $("#viewleadName").html(leadName);
    ShowDialog(true, "_assign");
}


/* Config validation */
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});





////////////////////////////////////////////////////////////////////////////////
// param: Mask & Value
// Example : formatCurrency("#,##0.00", 343434312321567.886);
////////////////////////////////////////////////////////////////////////////////
function formatCurrency(m, v) {
    if (!m || isNaN(+v)) {
        return v; //return as it is.
    }
    //convert any string to number according to formation sign.
    var v = m.charAt(0) == '-' ? -v : +v;
    var isNegative = v < 0 ? v = -v : 0; //process only abs(), and turn on flag.

    //search for separator for grp & decimal, anything not digit, not +/- sign, not #.
    var result = m.match(/[^\d\-\+#]/g);
    var Decimal = (result && result[result.length - 1]) || '.'; //treat the right most symbol as decimal
    var Group = (result && result[1] && result[0]) || ',';  //treat the left most symbol as group separator

    //split the decimal for the format string if any.
    var m = m.split(Decimal);
    //Fix the decimal first, toFixed will auto fill trailing zero.
    v = v.toFixed(m[1] && m[1].length);
    v = +(v) + ''; //convert number to string to trim off *all* trailing decimal zero(es)

    //fill back any trailing zero according to format
    var pos_trail_zero = m[1] && m[1].lastIndexOf('0'); //look for last zero in format
    var part = v.split('.');
    //integer will get !part[1]
    if (!part[1] || part[1] && part[1].length <= pos_trail_zero) {
        v = (+v).toFixed(pos_trail_zero + 1);
    }
    var szSep = m[0].split(Group); //look for separator
    m[0] = szSep.join(''); //join back without separator for counting the pos of any leading 0.

    var pos_lead_zero = m[0] && m[0].indexOf('0');
    if (pos_lead_zero > -1) {
        while (part[0].length < (m[0].length - pos_lead_zero)) {
            part[0] = '0' + part[0];
        }
    }
    else if (+part[0] == 0) {
        part[0] = '';
    }

    v = v.split('.');
    v[0] = part[0];

    //process the first group separator from decimal (.) only, the rest ignore.
    //get the length of the last slice of split result.
    var pos_separator = (szSep[1] && szSep[szSep.length - 1].length);
    if (pos_separator) {
        var integer = v[0];
        var str = '';
        var offset = integer.length % pos_separator;
        for (var i = 0, l = integer.length; i < l; i++) {

            str += integer.charAt(i); //ie6 only support charAt for sz.
            //-pos_separator so that won't trail separator on full length
            if (!((i - offset + 1) % pos_separator) && i < l - pos_separator) {
                str += Group;
            }
        }
        v[0] = str;
    }

    v[1] = (m[1] && v[1]) ? Decimal + v[1] : "";
    return (isNegative ? '-' : '') + v[0] + v[1]; //put back any negation and combine integer and fraction.
}

function removeWhiteSpaces(inputString) {
    // Remove the whitespaces at the beginning and end
    var s1 = inputString.replace(/^\s+|\s+$/g, "");
    // Remove all extra space between words in a string
    return s1.replace(/\s+/g, " ");
}

// Get URL parameter by name
function getURLParameter(name) {
    return decodeURIComponent((location.search.match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]);
}

// Close popup error request
// When have an action call a ajax function
// And this request is failure
function closePopupError() {
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
    $.fancybox.close();
}
function closePopup() {
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
    $.fancybox.close();
}
function showPopupError() {
    $('#fancybox-overlay').show();
    $('#popupErrorRequest').showPopup({
        width: 450
    });
}
function showDialError() {
    $('#fancybox-overlay').show();
    $('#popupDialError').showPopup({
        width: 450
    });
}

function showUploadError() {
    $('#fancybox-overlay').show();
    $('#popupErrorRequest').showPopup({
        width: 450
    });
}

function showCustomError(errorMessage) {
    if ((errorMessage.toLowerCase().indexOf("timeout") > -1) ||
	(errorMessage.toLowerCase().indexOf("expired") > -1)) {
        showPopupError();
    }
    else {
        $('#customErrorMessage').html(errorMessage);
        $('#fancybox-overlay').show();
        $('#popupCustomError').showPopup({
            width: 450
        });
    }
}

// Progress Bar
function openProcess() {
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
    $.fancybox($('#popup-process'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
}
function hideProcess() {
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
    $.fancybox.close();
}

// Open Prority Chart View
function openChartView() {
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
    $.fancybox($('#viewChartPriority'), {
        padding: 0,
        closeBtn: true,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return true;
        }
    });
    return false;
}

// Refresh JCF dropdown box
function RefreshDropdown(_dropdownId) {
    var tempEl = document.getElementById(_dropdownId);
    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
    jcf.customForms.replaceElement(_dropdownId);
    // Force to be executed after knockout rendering
    var str = "jcf.customForms.replaceElement('" + _dropdownId + "')";
    setTimeout(str, 0);
}


/////////////////////////// Preview Email /////////////////////////////////////
function OpenPreviewEmail(_emailOptionId) {
    var dataPost = { "id": _emailOptionId };
    var success = false;
    var isHtml;
    $.ajax({
        type: "POST",
        async: false,
        url: "/Email/IsHtml",
        data: dataPost,
        dataType: "json",
        success: function (returnData, textStatus, jqXHR) {
            if (returnData != null) {
                success = true;
                isHtml = returnData;
            }
            else {
                showPopupError();
            }
        },
        error: function (xhr, status, error) {
            showPopupError();
        }

    });      // End ajax post
    if (success) {
        showPreview(isHtml, _emailOptionId);
    }


}

function showPreview(isHtml, _emailOptionId) {
    if (isHtml.toString() == "true") {
        var url = "/Email/EmailPreviewHTML/" + _emailOptionId,
		widthPopup = 855,
		heightPopup = 600,
		leftPopup = (screen.width / 2) - (widthPopup / 2),
		topPopup = (screen.height / 2) - (heightPopup / 2);
        window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup + ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=0,toolbar=0,status=0');
    }
    else {
        var url = "/Email/EmailPreviewText/" + _emailOptionId,
		widthPopup = 850,
		heightPopup = 600,
		leftPopup = (screen.width / 2) - (widthPopup / 2),
		topPopup = (screen.height / 2) - (heightPopup / 2);
        window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup + ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=0,toolbar=0,status=0');
    }
}

function CheckFlashPlayerVersion() {
    var showInstallElement = true;
    if (swfobject.getFlashPlayerVersion().major !== 0) {
        if (swfobject.getFlashPlayerVersion().major < 11) {
            showInstallElement = true;
        }
        else {
            if (swfobject.getFlashPlayerVersion().major == 11) {
                if (swfobject.getFlashPlayerVersion().minor < 1) {
                    showInstallElement = true;
                }
                else {
                    showInstallElement = false;
                }
            }
            else {
                showInstallElement = false;
            }
        }
    }
    else {
        showInstallElement = true;
    }
    if ($('#InstallFlashPlayer') != undefined) {
        if (showInstallElement == true) {
            $('#InstallFlashPlayer').css("display", "block");
            $('#InstallFlashPlayer').html("This feature requires Flash version 11.5 or later.  <a href='http://get.adobe.com/flashplayer/' target='_blank'>Install Flash now</a>.<br />");
        }
        else {
            $('#InstallFlashPlayer').css("display", "none");
            $('#InstallFlashPlayer').html("");
        }
    }
    if ($('#InstallFlashPlayer1') != undefined) {
        if (showInstallElement == true) {
            $('#InstallFlashPlayer1').css("display", "block");
            $('#InstallFlashPlayer1').html("This feature requires Flash version 11.5 or later.  <a href='http://get.adobe.com/flashplayer/' target='_blank'>Install Flash now</a>.<br />");
        }
        else {
            $('#InstallFlashPlayer1').css("display", "none");
            $('#InstallFlashPlayer1').html("");
        }
    }
}